package cn.monkey.state.scheduler;

import cn.monkey.state.core.FetchStateGroup;
import cn.monkey.state.core.StateGroupPool;

public class SimpleSchedulerManager extends AbstractSchedulerManager {

    private final StateGroupPool stateGroupPool;

    public SimpleSchedulerManager(StateGroupPool stateGroupPool,
                                  StateGroupSchedulerFactory stateGroupSchedulerFactory,
                                  EventPublishSchedulerFactory eventPublishSchedulerFactory,
                                  SchedulerManagerConfig managerConfig) {
        super(stateGroupSchedulerFactory, eventPublishSchedulerFactory, managerConfig);
        this.stateGroupPool = stateGroupPool;
    }


    protected void findBestSchedulerAndTryAddStateGroup(String groupId, Object event, Object... args) {
        FetchStateGroup fetchStateGroup = this.stateGroupPool.findOrCreate(groupId, args);
        super.onFetchStateGroup(fetchStateGroup, event);
    }


    @Override
    public void addEvent(String groupId, Object event, Object... args) {
        if (!this.isRunning.get()) {
            throw new UnsupportedOperationException("schedulerManager has stopped");
        }
        this.findEventPublisherScheduler(groupId).publish(() -> this.findBestSchedulerAndTryAddStateGroup(groupId, event, args));
    }
}
